#!/usr/bin/env python
# Create: 2019/8/19
__author__ = '749B'
"""删除 UnManaged 端口
条件查找符合条件的端口后，直接一个一个调用DELETE方法删除
每一次删除都会打印日志并且记录到文件
"""

import logging.config
import requests

from sds.swis_login import swis

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'no_time': {
            'format': '{message}',
            'style': '{',
        },
        'with_time': {
            'format': '{asctime} {message}',
            'datefmt': '%Y-%m-%d %H:%M:%S',
            'style': '{',
        }
    },
    'handlers': {
        'stream': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'no_time',
        },
        'dailyfile': {
            'level': 'DEBUG',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': 'log/delete_interfaces.log',
            'when': 'D',
            'backupCount': 10,
            'encoding': 'utf-8',
            'formatter': 'with_time',
        },
    },
    'loggers': {
        '__main__': {
            'handlers': ['stream', 'dailyfile'],
            'level': 'DEBUG',
        },
    }
}

logging.config.dictConfig(LOGGING)
logger = logging.getLogger(__name__)


def run(mode='show', top=10):
    # 查找端口，Unmanaged，并且LastChange要在某个时间之前
    sql_str = "SELECT {top} FullName, InterfaceID, LastChange, Uri " \
              "FROM Orion.NPM.Interfaces " \
              "WHERE Unmanaged = true AND LastChange < '2018/08/01' " \
              "ORDER BY LastChange DESC"
    if mode == 'count':
        top = 0
    if top:
        sql_str = sql_str.format(top="TOP %s" % top)
    else:
        sql_str = sql_str.format(top='')
    results = swis.query(sql_str)
    if mode == 'show' or mode == 'count':
        for result in results['results']:
            print(result)
            if mode == 'count':
                print('count:', end=' ')
                break
        print(len(results['results']))
    elif mode == 'delete':
        for result in results['results']:
            delete(result)
    else:
        for result in results['results']:
            print(result)
        print("没有匹配的 mode")


def delete(result):
    swis.delete(result['Uri'])
    log_str = "ID:%s %s %s" % (result.get('InterfaceID'), result.get('LastChange'), result.get('FullName'))
    logger.info(log_str)


requests.packages.urllib3.disable_warnings()


if __name__ == '__main__':
    run('delete', 3)


